package com.fast.framework.config.security.handle;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.fast.framework.config.security.jwt.JwtTokenUtil;
import com.fast.framework.constant.HttpStatus;
import com.fast.framework.core.AjaxResult;
import com.fast.framework.core.domain.User;
import com.fast.framework.enums.JwtEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义退出处理类 返回成功
 *
 * @author lanyuankeji
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    private static final String tokenHeader = JwtEnum.tokenHeader.getValue();
    private static final String tokenHead = JwtEnum.tokenHead.getValue();
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        User loginUser = jwtTokenUtil.getLoginUser(request);
        if (ObjUtil.isNotNull(loginUser) && ObjUtil.isNull(SecurityContextHolder.getContext().getAuthentication())) {
            if (ObjUtil.isNotEmpty(loginUser)) {
                String userName = loginUser.getUsername();
                // 删除用户缓存记录
                jwtTokenUtil.delLoginUser(userName);
            }
            int code = HttpStatus.SUCCESS;
            String msg = StrUtil.format("注销成功", request.getRequestURI());
            // 获取响应输出流
            PrintWriter out = response.getWriter();
            // 构建响应数据对象
            AjaxResult bean = AjaxResult.error(code, msg);
            // 将响应数据对象转换为 JSON 字符串并写入响应输出流
            out.write(new ObjectMapper().writeValueAsString(bean));
            // 刷新输出流并关闭
            out.flush();
            out.close();
        }
    }
}
